package com.jfinal.weixin.api;

import com.jfinal.plugin.redis.Redis;
import com.jfinal.utils.Exceptions;
import com.jfinal.weixin.api.model.AccessToken;
import lombok.extern.slf4j.Slf4j;

/**
 * @author LarryKoo(larrykoo@126.com)
 * @date 2015-12-17
 */
@Slf4j
public class WxTestKit {

    private static String appid = "";
    private static String appSecret = "";

    /**
     * 缓存测试的 AccessToken
     *
     * @return
     */
    public static String getAccessToken() {
        String accessToken = "";
        try {
            String key = "WeChat:Keys:" + appid + ":TOKEN";
            if (Redis.use().exists(key)) {
                accessToken = Redis.use().get(key);
            } else {
                AccessToken at = AccessTokenApi.ice.getAccessToken(appid, appSecret);
                if (at.isAvailable()) {
                    accessToken = at.getAccess_token();
                    Redis.use().setex(key, at.getExpires_in(), accessToken);
                }
            }
        } catch (Exception e) {
            log.error("getAccessToken-Exception", e);
            throw Exceptions.unchecked(e);
        } finally {
            return accessToken;
        }
    }

}
